
#include <stdlib.h>
#include <string.h>

#include "imagerect.h"

void release_imageRect(ImageRect* ptr)
{
    free(ptr->data);
    free(ptr);
}

ImageRect* CreateImageRect(Image *img, int RGB, int offX, int offY, int w, int h){
    ImageRect* rect;
    int i;

    rect = (ImageRect*) malloc(sizeof(ImageRect));

    if (rect == NULL)
        return NULL;

    rect->colorsize = img->colorsize;
    rect->offsetX = offX;
    rect->offsetY = offY;
    rect->width = w;
    rect->height = h;
    rect->color = RGB;

    rect->data = malloc( rect->colorsize*w*h );

    unsigned char *dataptr;
    switch (RGB){
        case COLOR_RED:
            dataptr = (unsigned char*)img->r;
            break;
        case COLOR_GREEN:
            dataptr = (unsigned char*)img->g;
            break;
        case COLOR_BLUE:
            dataptr = (unsigned char*)img->b;
            break;
        default:
            return NULL;
    }

    for (i = 0; i < h; ++i){

//        for (j = 0; j < w; ++j){
//            ((unsigned char*) rect->data)[w*i + j] = dataptr[(img->width*(i+offY) + j+offX)*img->colorsize];
//        }
        memcpy(((unsigned char*)rect->data)+i*w, &(dataptr[(img->width*(i+offY) + offX)*img->colorsize]), w*img->colorsize);
    }

    return rect;
}


Image* transform_into_image(ImageRect* imgrect){

	Image* img = (Image*) malloc( sizeof(Image) );
	if (img == NULL) return NULL;

	img->width = imgrect->width;
	img->height = imgrect->height;
	img->colorsize = imgrect->colorsize;

    unsigned char* a[3];
    a[0] = (unsigned char*) calloc(imgrect->width*imgrect->height, img->colorsize);
    a[1] = (unsigned char*) calloc(imgrect->width*imgrect->height, img->colorsize);
    a[2] = (unsigned char*) malloc(imgrect->width*imgrect->height *img->colorsize);

    memcpy(a[2], imgrect->data, imgrect->width*imgrect->height * img->colorsize);

    switch (imgrect->color){
        case COLOR_RED:
            img->r = a[2];
            img->g = a[0];
            img->b = a[1];
            break;
        case COLOR_GREEN:
            img->r = a[0];
            img->g = a[2];
            img->b = a[1];
            break;
        case COLOR_BLUE:
            img->r = a[0];
            img->g = a[1];
            img->b = a[2];
            break;
        default:
            return NULL;
    }

	return img;
}
